<?php

class PaypalController extends Controller {

    public function init() {
	if (user()->isGuest) {
	    $this->redirect(SITE_NAME_URL);
	}
    }

    /**
     * confirm payment success
     * @throws CHttpException
     */
    public function actionConfirm() {
	$token = trim($_GET['token']);
	$payerId = trim($_GET['PayerID']);

	//update model
	$model = Invoice::model()->find('payment_code = :payment_code', array(':payment_code' => $token));

	if (!$model) {
	    //error!!
	    throw new CHttpException(404, 'Page was not exists');
	}

	$result = Yii::app()->Paypal->GetExpressCheckoutDetails($token);

	$result['PAYERID'] = $payerId;
	$result['TOKEN'] = $token;
	$result['ORDERTOTAL'] = $model->total;

	//Detect errors
	if (!Yii::app()->Paypal->isCallSucceeded($result)) {
	    if (Yii::app()->Paypal->apiLive === true) {
		//Live mode basic error message
		$error = 'We were unable to process your request. Please try again later';
	    } else {
		//Sandbox output the actual error message to dive in.
		$error = $result['L_LONGMESSAGE0'];
	    }
	    echo $error;
	    Yii::app()->end();
	} else {
	    $paymentResult = Yii::app()->Paypal->DoExpressCheckoutPayment($result);
	    //Detect errors
	    if (!Yii::app()->Paypal->isCallSucceeded($paymentResult)) {
		if (Yii::app()->Paypal->apiLive === true) {
		    //Live mode basic error message
		    $error = 'We were unable to process your request. Please try again later';
		} else {
		    //Sandbox output the actual error message to dive in.
		    $error = $paymentResult['L_LONGMESSAGE0'];
		}
		echo $error;
		Yii::app()->end();
	    } else {
		//payment was completed successfully
		//update payment status
		$model->status = Invoice::STATUS_APPROVE;

		if ($model->model == Invoice::MODEL_USER) {
		    //update ad expired
		    $user = User::model()->findByPk($model->model_id);

		    if ($user) {
			//get duration
			$params = CJSON::decode($model->params);

			//if ads is expired or created new
			if ($user->expired_time_msg < time()) {

			    switch ($params['duration']) {

				case "price_6_month":
				    $user->expired_time_msg = strtotime('+6 months');
				    break;
				case "price_one_year":
				    $user->expired_time_msg = strtotime('+1 year');
				    break;
				case "price_3_month": default:
				    $user->expired_time_msg = strtotime('+3 months');
				    break;
//				    case "price_two_week":
//					$ad->expired_time_msg = strtotime('+2 weeks');
//					break;
//				    case "price_one_month": default:
//					$ad->expired_time_msg = strtotime('+1 month');
//					break;
			    }
			} else {
			    //if user's ads is not expired, for renew
			    //get Odd time
			    $oddTime = $user->expired_time_msg - time();
			    switch ($params['duration']) {
				case "price_6_month":
				    $user->expired_time_msg = strtotime('+6 months') + $oddTime;
				    break;
				case "price_one_year":
				    $user->expired_time_msg = strtotime('+1 year') + $oddTime;
				    break;
				case "price_3_month": default:
				    $user->expired_time_msg = strtotime('+3 months') + $oddTime;
				    break;
			    }
			}
			$user->is_send_mail = User::NOT_SEND_MAIL;
			$user->is_send_mail_before = User::NOT_SEND_MAIL;
			$user->save();
			user()->setModel($user);
		    }
		}
		if ($model->save()) {
		    $this->render('confirm');
		}
	    }
	}
    }

    public function actionCancel() {
	//The token of the cancelled payment typically used to cancel the payment within your application
	$token = $_GET['token'];
	$this->render('cancel');
    }

    public function actionIndex() {

	if (isset($_POST['submit'])) {
	    if ($_POST['package']) {

		$price = intval(settings()->get('price_packages', $_POST['package']));

		$params = array(
		    'duration' => $_POST['package']
		);
		$this->_redirectPaypal($price, $params);
	    } else {
		Yii::app()->user->setFlash('error', '<div class="alert alert-error">Please select one packages before submitting.</div>');
	    }
	}
	$this->render('index');
    }

    /**
     *
     */
    private function _redirectPaypal($price, $params = array()) {

	$paymentInfo = array();
	$paymentInfo['Order']['theTotal'] = $price;
	$paymentInfo['Order']['description'] = 'Pay for send message';
	$paymentInfo['Order']['quantity'] = '1';

	// call paypal
	$result = Yii::app()->Paypal->SetExpressCheckout($paymentInfo);

	//Detect Errors
	if (!Yii::app()->Paypal->isCallSucceeded($result)) {
	    if (Yii::app()->Paypal->apiLive === true) {
		//Live mode basic error message
		$error = 'We were unable to process your request. Please try again later';
	    } else {
		//Sandbox output the actual error message to dive in.
		$error = $result['L_LONGMESSAGE0'];
	    }

	    echo $error;
	    Yii::app()->end();
	} else {
	    // send user to paypal
	    $token = urldecode($result["TOKEN"]);
	    $payPalURL = Yii::app()->Paypal->paypalUrl . $token;

	    //add new invoice
	    $invoice = new Invoice;
	    $invoice->attributes = array(
		'model' => Invoice::MODEL_USER,
		'model_id' => user()->id,
		'payment_method' => 'paypal',
		'payment_code' => $token,
		'status' => Invoice::STATUS_PENDING,
		'params' => CJSON::encode($params),
		'create_by' => user()->id,
		'total' => $price
	    );

	    if ($invoice->save()) {
		$this->redirect($payPalURL);
	    } else {
		die('An error occured, please try again!');
	    }
	}
    }

    /*
     * Reactive your post
     */

    public function actionRe_active() {

	//get duration of this post
	$model = Invoice::model()->find('model=:model and model_id=:model_id', array(
	    ':model' => Invoice::MODEL_USER,
	    ':model_id' => user()->id
	));

	if ($model) {
	    $duration = CJSON::decode($model->params);
	    $price = settings()->get('price_packages', $duration['duration']);
	    $params = array(
		'duration' => $duration['duration']
	    );

	    $this->_redirectPaypal($price, $params);
	} else {
	    throw new CHttpException(404, 'Page was not existed');
	}
    }

}

